package models

// CartItem 结构体表示购物车中的项
type CartItem struct {
    UserID     int     `json:"user_id"`
    ProductID  int     `json:"product_id"`
    ProductName string  `json:"product_name"`
    Quantity   int     `json:"quantity"`
    Price      float64 `json:"price"`
}

// 获取指定用户的购物车，包括产品名称和价格
func GetCartByUserID(userID int) ([]CartItem, error) {
    rows, err := db.Query(`
        SELECT c.user_id, c.product_id, c.quantity, p.name, p.price
        FROM cart c
        JOIN products p ON c.product_id = p.id
        WHERE c.user_id = ?`, userID)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    var cart []CartItem
    for rows.Next() {
        var item CartItem
        err := rows.Scan(&item.UserID, &item.ProductID, &item.Quantity, &item.ProductName, &item.Price)
        if err != nil {
            return nil, err
        }
        cart = append(cart, item)
    }
    return cart, nil
}

// 将商品添加到购物车
func AddToCart(item CartItem) error {
    // 检查购物车中是否已经存在该商品
    var existingQuantity int
    err := db.QueryRow("SELECT quantity FROM cart WHERE user_id = ? AND product_id = ?", item.UserID, item.ProductID).
        Scan(&existingQuantity)
    
    if err == nil { // 如果商品已存在，更新数量
        newQuantity := existingQuantity + item.Quantity
        stmt, err := db.Prepare("UPDATE cart SET quantity = ? WHERE user_id = ? AND product_id = ?")
        if err != nil {
            return err
        }
        _, err = stmt.Exec(newQuantity, item.UserID, item.ProductID)
        if err != nil {
            return err
        }
        return nil
    } else if err.Error() == "sql: no rows in result set" { 
        // 如果商品不存在，插入新记录
        stmt, err := db.Prepare("INSERT INTO cart(user_id, product_id, quantity) VALUES(?, ?, ?)")
        if err != nil {
            return err
        }
        defer stmt.Close()

        _, err = stmt.Exec(item.UserID, item.ProductID, item.Quantity)
        if err != nil {
            return err
        }
        return nil
    } else {
        return err // 如果查询出错
    }
}

// 从购物车删除商品
func DeleteFromCart(userID, productID int) (int64, error) {
    stmt, err := db.Prepare("DELETE FROM cart WHERE user_id = ? AND product_id = ?")
    if err != nil {
        return 0, err
    }
    defer stmt.Close()

    result, err := stmt.Exec(userID, productID)
    if err != nil {
        return 0, err
    }

    // 获取删除的行数
    rowsAffected, err := result.RowsAffected()
    if err != nil {
        return 0, err
    }

    return rowsAffected, nil
}
